package com.movecar.ui;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.listview.WaterFallListView;
import com.movecar.listview.WaterFallListView.IXListViewListener;
import com.movecar.model.MoreInfoManageBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 消息管理
 * 
 * @author Zhao.JQ
 * 
 */
public class MoreInfoManagelActivity extends Activity implements OnClickListener, IXListViewListener {

	private ImageLoader imageLoader = null;
	private CustomProgressDialog progressDialog = null;
	private String pageNo = "0";
	private List<MoreInfoManageBean> mDataList;
	private List<MoreInfoManageBean> resultList;
	private boolean flgMore = false;
	protected WaterFallListView mXList;
	private DataAdapter dataAdapter;
	private String csId = "0";

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_info_manage);
		imageLoader = ImageLoader.getInstance();
		csId = getIntent().getStringExtra("csId");
		initView();

	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView() {
		mXList = (WaterFallListView) findViewById(R.id.list);
		mXList.setPullRefreshEnable(true);
		mXList.setPullLoadEnable(true);
		mXList.setXListViewListener(this);
		dataAdapter = new DataAdapter(MoreInfoManagelActivity.this);
		mXList.setAdapter(dataAdapter);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("消息管理");
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		Button delete = (Button) findViewById(R.id.btn_right);
		delete.setVisibility(View.VISIBLE);
		delete.setBackgroundResource(R.drawable.btn_share_delete);
		delete.setOnClickListener(this);
		startProgressDialog();
		getNoticeList();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btn_left:
			finish();
			break;
		case R.id.btn_right:

			CustomDialog.Builder customBuilder = new CustomDialog.Builder(MoreInfoManagelActivity.this);
			ImageView img = new ImageView(MoreInfoManagelActivity.this);
			img.setImageResource(R.drawable.ic_launcher);
			customBuilder.setImgIcon(img).setMessage("确认删除?")

			.setPositiveButton("确认", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startProgressDialog();
					deleteSahre();
					dialog.dismiss();

				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.dismiss();

				}
			});
			customBuilder.create().show();
			break;
		default:
			break;
		}

	}

	/**
	 * 删除消息列表
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void deleteSahre() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "delAllNoticeNew2"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				if (null != result) {

					if ("0".equals(result)) {
						Alert.warn(MoreInfoManagelActivity.this, "删除成功！");
						getNoticeList();
					} else {
						Alert.warn(MoreInfoManagelActivity.this, result);
					}
				} else {
					Alert.warn(MoreInfoManagelActivity.this, "系统异常!");
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(MoreInfoManagelActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);

	}

	@SuppressWarnings("unchecked")
	private void getNoticeList() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryNoticeListNew1"));
		// 添加要传递的参数

		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("pageNo", pageNo));
		params.add(new BasicNameValuePair("csId", csId));
		params.add(new BasicNameValuePair("state", "0"));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				stopProgressDialog();
				Type type = new TypeToken<List<MoreInfoManageBean>>() {
				}.getType();
				Gson gson = new Gson();
				String result = (String) object;

				Object fromJson = gson.fromJson(result, type);
				try {
					mDataList = (List<MoreInfoManageBean>) fromJson;
				} catch (Exception e) {
					return;
				}
				if (mDataList != null) {
					resultList = new ArrayList<MoreInfoManageBean>();
					if (flgMore) {
						if (mDataList.size() == 0) {
							Alert.warn(MoreInfoManagelActivity.this, "已经加载全部");
							if (!"1".equals(pageNo)) {
								pageNo = String.valueOf(Integer.parseInt(pageNo) - 1);
							} else {
								pageNo = "0";
							}
							resetXList();
						} else {
							resultList.clear();

							for (MoreInfoManageBean bean : mDataList) {
								resultList.add(bean);
							}
							dataAdapter.addItemLast(resultList);
							resetXList();

						}
					} else {

						if (mDataList.size() == 0) {
							Alert.warn(MoreInfoManagelActivity.this, "目前无内容");

							resetXList();
						}
						resultList.clear();

						for (MoreInfoManageBean bean : mDataList) {
							resultList.add(bean);
						}
						dataAdapter.addItemTop(resultList);
						// dataAdapter.notifyDataSetChanged();

						resetXList();
					}

				} else {
					Alert.warn(MoreInfoManagelActivity.this, "系统异常");
					resetXList();
				}

			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(MoreInfoManagelActivity.this, "与服务器连接失败，请检查网络");
				resetXList();

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	class DataAdapter extends BaseAdapter {

		private Activity activity;
		private LayoutInflater inflater;
		private LinkedList<MoreInfoManageBean> resultList;

		DataAdapter(Activity activity) {

			this.activity = activity;
			inflater = LayoutInflater.from(activity);
			resultList = new LinkedList<MoreInfoManageBean>();
		}

		public void addItemLast(List<MoreInfoManageBean> datas) {
			resultList.addAll(datas);
		}

		public void addItemTop(List<MoreInfoManageBean> datas) {
			resultList.clear();
			for (MoreInfoManageBean info : datas) {
				resultList.add(info);
			}
		}

		@Override
		public int getCount() {

			return resultList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return resultList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			// final ViewHolder viewHolder;
			final MoreInfoManageBean bean = resultList.get(position);
			View itemView = null;
			if (view == null) {
				// viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.more_info_manage_item, null);
				itemView = view;
				view.setTag(itemView);

				// view.setTag(viewHolder);
			} else {
				itemView = (View) view.getTag();
				// viewHolder = (ViewHolder) view.getTag();
			}
			ImageView info_type_img = (ImageView) view.findViewById(R.id.info_type_img);

			TextView info_content = (TextView) view.findViewById(R.id.info_content);
			TextView info_time = (TextView) view.findViewById(R.id.info_time);
			RelativeLayout navi_new_tip = (RelativeLayout) view.findViewById(R.id.navi_new_tip);
			if ("0".equals(bean.getType())) {
				info_type_img.setImageResource(R.drawable.icon_info_manage);
			} else if ("1".equals(bean.getType())) {
				info_type_img.setImageResource(R.drawable.icon_info_manage);
			} else if ("2".equals(bean.getType())) {
				info_type_img.setImageResource(R.drawable.icon_info_manage);
			} else if ("3".equals(bean.getType())) {
				info_type_img.setImageResource(R.drawable.icon_info_manage);
			} else {

			}
			// if ("0".equals(bean.getNoticeFlag())) {
			// navi_new_tip.setVisibility(View.GONE);
			// } else {
			// navi_new_tip.setVisibility(View.VISIBLE);
			// }
			info_content.setText(bean.getContent());
			info_time.setText(bean.getCreateDate());
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if ("0".equals(resultList.get(position).getType())) {
					} else if ("1".equals(resultList.get(position).getType())) {
						Intent intent = new Intent();
						intent.setClass(MoreInfoManagelActivity.this, GroupDetailActivity.class);
						intent.putExtra("messageId", resultList.get(position).getRelateId());
						startActivity(intent);
					} else if ("2".equals(resultList.get(position).getType())) {
						startActivity(new Intent(getApplicationContext(), ActivityAddFriends.class));
					} else if ("3".equals(resultList.get(position).getType())) {
					} else {

					}
				}
			});
			return view;
		}
	}

	protected void resetXList() {

		mXList.setRefreshTime(new SimpleDateFormat("H:mm", Locale.CHINA).format(new Date()));
		mXList.stopRefresh();
		mXList.stopLoadMore();
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	public void onRefresh() {
		flgMore = false;
		resultList.clear();
		pageNo = "0";
		getNoticeList();
	}

	@Override
	public void onLoadMore() {
		flgMore = true;
		pageNo = String.valueOf(Integer.parseInt(pageNo) + 1);
		getNoticeList();

	}
}
